// url: https://leetcode.cn/problems/remove-duplicates-from-sorted-array/?envType=study-plan-v2&envId=top-interview-150
package interview_classic.array_or_str;


public class Solution27 {

    // way1: 单指针
    public int removeElement1(int[] nums, int val) {
        int validLen = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val) {
                nums[validLen++] = nums[i];
            }
        }
        return validLen;
    }

    // way2: 双指针
    public int removeElement(int[] nums, int val) {
        if (nums.length == 0) return 0;
        int l = 0, r = nums.length - 1;
        while (l < r) {
            while (nums[l] != val && l < r) {
                l++;
            }
            while(nums[r] == val && l < r) {
                r--;
            }
            swap(nums, l, r);
        }
        return nums[l] == val ? l : l + 1;
    }

    private void swap(int[] nums, int l, int r) {
        int t = nums[l];
        nums[l] = nums[r];
        nums[r] = t;
    }
}
